package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.LiuYan_Detail_Adapter;
import com.example.xianji.bean.LiuYan;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.MyListview;
import com.example.xianji.widgets.PullToRefreshLayout_No_LoadMore;
import com.example.xianji.widgets.PullToRefreshLayout_No_LoadMore.OnRefreshListener;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class Main_LiuYan_DetailsActivity extends Activity implements OnClickListener, OnRefreshListener {
    private ImageView my_receive_liuyan_details_back;
    //    private SharedPreferences sp;
//    private Editor ed;
    private ArrayList<LiuYan> liuyan_list = new ArrayList<LiuYan>();
    private LiuYan_Detail_Adapter mLiuYan_Detail_Adapter;
    private PullToRefreshLayout_No_LoadMore liuyan_detail_PullToRefreshLayout_no_Loadmore;
    private MyListview liuyan_detail_mylistview;
    private ClipboardManager clipboard;
    private InputMethodManager manager;
    private EditText edittext_contant;
    private String btob, otherpart;
    private Button liuyan_send;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == 1) {
                liuyan_detail_mylistview.setAdapter(mLiuYan_Detail_Adapter);
                liuyan_detail_PullToRefreshLayout_no_Loadmore.refreshFinish(PullToRefreshLayout_No_LoadMore.SUCCEED);
            }
            if (msg.what == 2) {
                my_liuyan_detail();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__liu_yan__details);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        //	XJApplication.getInstance().addActivity(this);
        clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        edittext_contant = (EditText) findViewById(R.id.edittext_contant);
        liuyan_send = (Button) findViewById(R.id.liuyan_send);
        hideKeyboard();

        liuyan_detail_PullToRefreshLayout_no_Loadmore = (PullToRefreshLayout_No_LoadMore) findViewById(R.id.liuyan_detail_PullToRefreshLayout_no_Loadmore);
        liuyan_detail_mylistview = (MyListview) findViewById(R.id.liuyan_detail_mylistview);

        mLiuYan_Detail_Adapter = new LiuYan_Detail_Adapter(this, liuyan_list);

        my_liuyan_detail();

        my_receive_liuyan_details_back = (ImageView) findViewById(R.id.my_receive_liuyan_details_back);
        my_receive_liuyan_details_back.setOnClickListener(this);
        liuyan_detail_PullToRefreshLayout_no_Loadmore.setOnRefreshListener(this);
        liuyan_send.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.my_receive_liuyan_details_back) {
            this.finish();
        } else if (v.getId() == R.id.liuyan_send) {
            send_liuyan();
        }
    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void my_liuyan_detail() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("btob", getIntent().getStringExtra("liuyan_detail_id"));
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//        map.put("token", sp.getString("xianji_token", ""));
        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.my_liuyan_detail,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        liuyan_list.clear();
                        JSONArray array = response.getJSONArray("data");
                        JSONArray array1 = array.getJSONArray(0);
                        for (int i = 0; i < array1.length(); i++) {
                            JSONObject object1 = array1.getJSONObject(i);
                            LiuYan mLiuYan = new LiuYan();
                            mLiuYan.setAuthor(object1.getInt("author"));
                            mLiuYan.setBoothscase(object1.getString("boothscase"));
                            mLiuYan.setCreated_at(object1.getString("created_at"));
                            mLiuYan.setDetail(object1.getString("detail"));
                            mLiuYan.setNickname(object1.getJSONObject("usrs").getString("nickname"));

                            btob = object1.getString("btob");
                            if (object1.getInt("author") == PreferenceEngine.getInstance().getInt(Constant.SP.NAME, Constant.SP.KEY_UID, 0)) {
//                            if (object1.getInt("author") == sp.getInt("uid", 0)) {
                                otherpart = object1.getString("otherpart");
                            }
                            liuyan_list.add(mLiuYan);
                        }
                    }
                    handler.sendEmptyMessage(1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }


    public void send_liuyan() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("details", edittext_contant.getText().toString());
        map.put("btob", btob);
        map.put("otherpart", otherpart);
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//        map.put("token", sp.getString("xianji_token", ""));
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.fuwu_liuyan,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(Main_LiuYan_DetailsActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        hideKeyboard();
                        edittext_contant.setText("");
                        handler.sendEmptyMessage(2);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    @Override
    public void onRefresh(PullToRefreshLayout_No_LoadMore pullToRefreshLayout) {
        my_liuyan_detail();
    }

    @Override
    public void onLoadMore(PullToRefreshLayout_No_LoadMore pullToRefreshLayout) {
        liuyan_detail_PullToRefreshLayout_no_Loadmore.loadmoreFinish(PullToRefreshLayout_No_LoadMore.SUCCEED);
    }
}
